package org.nowcoder.leetcode.BTree;

import java.util.*;

/**
 * Title  : 501. Find Mode in Binary Search Tree
 * Source : https://leetcode.cn/problems/find-mode-in-binary-search-tree/description/
 * Author : XrazYang
 * Date   : 2024-04-19
 */

public class LeetCode_501 {

    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int[] findMode(TreeNode root) {
        ArrayDeque<TreeNode> sta = new ArrayDeque<>();
        Map<Integer, Integer> map = new HashMap<>();
        TreeNode current = root;
        while (current != null || !sta.isEmpty()) {
            if (current != null) {
                sta.push(current);
                current = current.left;
            } else {
                current = sta.pop();
                int n = map.getOrDefault(current.val, 0);
                map.put(current.val, n + 1);
                current = current.right;
            }
        }
        int max = map.values().stream().max(Integer::compareTo).get();
        List<Integer> result = new ArrayList<>();
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() == max) {
                result.add(entry.getKey());
            }
        }
        int[] results = new int[result.size()];
        for (int i = 0; i < result.size(); i++) {
            results[i] = result.get(i);
        }
        return results;
    }
}
